import 'dart:async';
import 'dart:io';

import 'package:bigegg/common/log/xmm_logcat.dart';
import 'package:bigegg/data/repository/xmm_remote_repository.dart';
import 'package:bigegg/utils/xmm_toast_util.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
import 'package:in_app_purchase_storekit/store_kit_wrappers.dart';

class XmmApplyPayUtils {

  StreamSubscription<List<PurchaseDetails>>? _subscription;

  /// 苹果内购 (购买)
  Future<void> applePay(Map dataMap,
      {Function(String goodsCode)? callback}) async {
    final Stream<List<PurchaseDetails>> purchaseUpdated =
        InAppPurchase.instance.purchaseStream;
    _subscription?.cancel();
    _subscription =
        purchaseUpdated.listen((List<PurchaseDetails> purchaseDetailsList) {
      _listenToPurchaseUpdated(purchaseDetailsList, dataMap, callback: callback);
    }, onDone: () {
      _subscription?.cancel();
      XmmXLogcat.d('=applePay=====onDone');
    }, onError: (Object error) {
      XmmXLogcat.e(error);
      XmmToastUtils.show(error.toString());
    });

    final bool isAvailable = await InAppPurchase.instance.isAvailable();
    if (!isAvailable) {
      XmmToastUtils.show(
          'The store cannot be reached, check your network connection please.');
      return;
    }

    if (Platform.isIOS) {
      final InAppPurchaseStoreKitPlatformAddition iosPlatformAddition =
          InAppPurchase.instance
              .getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
      await iosPlatformAddition.setDelegate(XmmPaymentQueueDelegate());
    }

    Set<String> ids = {dataMap['goodsCode']};
    final ProductDetailsResponse productDetailResponse =
        await InAppPurchase.instance.queryProductDetails(ids);

    if (productDetailResponse.error != null) {
      XmmToastUtils.show('Failed to obtain product information.');
      return;
    }

    if (productDetailResponse.productDetails.isEmpty) {
      XmmToastUtils.show('No product');
      return;
    }
    List<ProductDetails> _products = productDetailResponse.productDetails;
    // 查询成功
    ProductDetails productDetails = _products[0];
    PurchaseParam purchaseParam = PurchaseParam(
      productDetails: productDetails,
      applicationUserName: '${dataMap['orderNo']}',
    );
    //向苹果服务器发起支付请求
    var res = await InAppPurchase.instance
        .buyConsumable(purchaseParam: purchaseParam);
    XmmXLogcat.d('buyConsumable result:  $res');
  }

  Future<void> _listenToPurchaseUpdated(
    List<PurchaseDetails> purchaseDetailsList,
    Map dataMap, {
    Function(String goodsCode)? callback,
  }) async {
    XmmXLogcat.d('===>>>_listenToPurchaseUpdated  callback');
    for (final PurchaseDetails purchaseDetails in purchaseDetailsList) {
      XmmXLogcat.d(
          '===>>>_listenToPurchaseUpdated  status=${purchaseDetails.status}  productID=${purchaseDetails.productID}  '
          'transactionDate=${purchaseDetails.transactionDate}'
          'purchaseID=${purchaseDetails.purchaseID}  transactionDate=${purchaseDetails.transactionDate}'
          'verificationData.localVerificationData=${purchaseDetails.verificationData.localVerificationData}'
          'verificationData.serverVerificationData=${purchaseDetails.verificationData.serverVerificationData}'
          'verificationData.source=${purchaseDetails.verificationData.source}');
      if (purchaseDetails.status == PurchaseStatus.pending) {
        /// 等待购买中
      } else if (purchaseDetails.status == PurchaseStatus.canceled) {
        /// 取消订单
        InAppPurchase.instance.completePurchase(purchaseDetails);
      } else {
        if (purchaseDetails.status == PurchaseStatus.error) {
          /// 购买出错
          XmmToastUtils.show('Purchase error');
          InAppPurchase.instance.completePurchase(purchaseDetails);
        } else if (purchaseDetails.status == PurchaseStatus.purchased ||
            purchaseDetails.status == PurchaseStatus.restored) {
          if (purchaseDetails.pendingCompletePurchase) {
            await InAppPurchase.instance.completePurchase(purchaseDetails);
          }
          if (purchaseDetails.productID == dataMap['goodsCode']) {
            await _deliverProduct(purchaseDetails, dataMap, callback: callback);
          }
        }
      }
    }
  }

  /// 调用后台接口,发放商品
  Future<void> _deliverProduct(
    PurchaseDetails purchaseDetails,
    Map dataMap, {
    Function(String goodsCode)? callback,
  }) async {
    String code = dataMap['goodsCode'];
    String payload = purchaseDetails.verificationData.serverVerificationData;
    String transactionId = purchaseDetails.purchaseID!;
    var resp = await XmmRemoteRepository().coinRechargePayment(
      dataMap['orderNo'],
      payload,
      transactionId,
    );
    if (resp.success) {
      callback?.call(code);
    }
  }
}

class XmmPaymentQueueDelegate implements SKPaymentQueueDelegateWrapper {
  @override
  bool shouldContinueTransaction(
    SKPaymentTransactionWrapper transaction,
    SKStorefrontWrapper storefront,
  ) {
    return true;
  }

  @override
  bool shouldShowPriceConsent() {
    return false;
  }
}
